package Search;
import java.util.Iterator;

import Cache.Cache;
import DataTags.DataTagsAdapter;
import DataTags.DataTagsToFiles;
import DataTags.files;

/**
 * With this class ,the user can search for files through their tags
 *@author Oz
 *
 */
public class Search  {

	protected DataTagsAdapter myDataTags;
	protected Cache cacheFileTags;
	protected Cache cacheTagsOfFile;
	/**
	 * this is the search c-tor
	 * 
	 */
	public Search(DataTagsAdapter Tags){
		int n=10;//can be any other size we want
		System.out.println("Search Screen Created");
		cacheFileTags=new Cache(n);
		cacheTagsOfFile=new Cache(n);
		myDataTags=Tags;
	}
	/**
	 * get all the tags that exist in our tagging system.
	 * @return allmyTags - String[]
	 *
	 */
	public String[]  getAllTags() {
		Iterator<DataTagsToFiles> it=myDataTags.simpleSearchAllTags().iterator();
		String allTags="";
		String []allmyTags ;
		while (it.hasNext()){
			allTags=allTags+it.next().getTag()+"@";
			
		}
		allmyTags=allTags.split("@");
		return allmyTags;
	}
	/**
	 *  get all files that have tagging (we track them in our tagging system)
	 *  @return allmyFiles- String[]
	 */
	public String[]  getAllFiles() {
		Iterator<files> it=myDataTags.simpleSearchAllFiles().iterator();
		String allFiles="";
		String []allmyFiles ;
		while (it.hasNext()){
			allFiles=allFiles+it.next().getName()+"@";
			
		}
		allmyFiles=allFiles.split("@");
		return allmyFiles;
	}
	/**
	 * Description of the method search.
	 * @param searchItem - String
	 * @param flag -boolean
	 *@return st- String
	 */
	public String searchThis(String searchItem,boolean flag) {
		//System.out.println("Looking for something");
		String st="";
		searchItem=searchItem.replace('*', '%');
		if(flag)/* searchItem is filename*/
		{
			if(cacheFileTags.contains(searchItem)){
				st=cacheFileTags.getVal(searchItem);
				System.out.println("tags in cache");
				return st;
			}
			
		}
		else{
			if(cacheTagsOfFile.contains(searchItem)){
				st=cacheTagsOfFile.getVal(searchItem);
				System.out.println("files in cache");
				return st;
			}
		}
		//String tags;
		System.out.println("This file name is not in the cache");
		st=myDataTags.searchFor(searchItem,flag);
		//System.out.println("tags from DB= "+tags);
		if(!st.isEmpty()){
			if (flag){
				cacheFileTags.putTo(searchItem,st);
			}
			else{
				cacheTagsOfFile.putTo(searchItem,st);
			}
		}
		return st;
		
			
		
	}
	/**
	 * opens the shell and prints to console
	 */
	public void Open(){
		System.out.println("Search GUI Window opened");
	}
	//passes the flush command on to DataTagsAdapter
	public void Flush(){
		myDataTags.FlushTags();
	}
	public DataTagsAdapter getDataTagsAdapter(){
		return myDataTags;
	}
	

}